package cn.xiaobai.springswagger.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

/**
 * knife4j配置(针对多个参数)
 * 目前只配置到单个参数进行修注入
 *
 * @author yangdaji
 * @date 2021/10/31 11:34
 */
@Slf4j
@EnableSwagger2WebMvc
@EnableConfigurationProperties(SwaggerProperties.class)
public class Knife4jAutoConfig implements InitializingBean {


    /**
     * swagger集成bean(2.0)
     */
    private SwaggerProperties swaggerProperties;

    /**
     * 处理多个元数据
     */
    private DefaultListableBeanFactory defaultListableBeanFactory;


    public Knife4jAutoConfig(SwaggerProperties swaggerProperties
            , DefaultListableBeanFactory defaultListableBeanFactory) {
        this.swaggerProperties = swaggerProperties;
        this.defaultListableBeanFactory = defaultListableBeanFactory;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            apiConfigRegister();
        } catch (Exception e) {
            log.error("swagger api register fail : {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private void apiConfigRegister() {
        this.swaggerProperties.getApis().forEach((e) -> {
            String apiBeanName = e.getBasePackage();
            log.info("{} -->> Injection SwaggerAPI --->>> {}...", this.swaggerProperties.getAppName(), apiBeanName);
            Docket docket = (new Docket(DocumentationType.SWAGGER_2)).groupName(e.getGroupName())
                    .apiInfo((new ApiInfoBuilder())
                            .title(e.getInfo().getTitle())
                            .description(e.getInfo().getDescription())
                            .contact(new Contact(e.getContact().getName(), e.getContact().getUrl(), e.getContact().getEmail()))
                            .version(e.getInfo().getVersion()).build())
                    .select().apis(RequestHandlerSelectors.basePackage(e.getBasePackage()))
                    .paths(PathSelectors.any()).build().pathMapping("/");
            this.defaultListableBeanFactory.registerSingleton(apiBeanName, docket);
        });
    }
}
